from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from app01.models import Users
from app01.utils.fieldshtml import fields_to_html, fields_to_save
from app01.utils.modelform import UserForm


# 用户列表
def user_list(request):
    if request.method == 'GET':
        users = Users.objects.all()
        form = UserForm(data=request.POST)
        # f = list(users.values().first())
        # print(Users._meta.model_name)
        select_str, dicts = fields_to_html(request.session['info']['employeeid'], Users)
        # print(dicts)
        context = {
            'fields': dicts,
            'select': select_str,
            'form': form,
            'users': users,
            'active5': 'active',
            'title': '用户管理'
        }
        return render(request, 'user_list.html', context)


# 编辑用户
# ajax方式
@csrf_exempt  # 免除 CSRF 验证
def user_edit(request):
    form = UserForm(data=request.POST)  # data:提交的数据；instance：保存到数据库的哪条记录
    nid = request.POST.get('nid')
    row = Users.objects.filter(id=nid).values('employeeid', 'name', 'password', 'admin').first()  # 取得需要修改的记录

    if not row:
        # 没找到记录数据
        return JsonResponse({'status': False, 'errors': '数据不存在.'})

    result = {
        'status': True,
        'data': row
    }
    # print(result)
    return JsonResponse(result)


# 传统方式提交保存
def user_password(request):
    if request.method == 'GET':
        return render(request, 'user_password.html')
    # 数据校验
    eid = request.POST.get('eid')
    pd = request.POST.get('password1')
    row = Users.objects.filter(employeeid=eid).first()  # 取得需要修改的记录
    row.password = pd
    row.save()
    return render(request, 'user_password.html', {'msg': '密码修改成功！'})


# ajax方式添加用户
@csrf_exempt  # 免除 CSRF 验证
def user_save(request):
    eid = request.GET.get('eid')
    print(eid)
    if int(eid) == -1:  # -1：表示新增；
        # 获取提交的数据
        form = UserForm(data=request.POST)
        if form.is_valid():
            # 数据合法,保存到数据库
            form.save()
            return JsonResponse({'status': True})
        # ensure_ascii=True会将中文转换为编码 {"user": "\u738b", "password": 123456}
        return JsonResponse({'status': False, 'errors': form.errors}, json_dumps_params={'ensure_ascii': False})

    if int(eid) >= 0:  # >=0：表示编辑ID为EDIT_ID的记录
        row = Users.objects.filter(id=eid).first()
        if row:
            form = UserForm(data=request.POST, instance=row)  # data:提交的数据；instance：保存到数据库中要修改的记录
            if form.is_valid():
                form.save()
                return JsonResponse({'status': True})
            return JsonResponse({'status': False, 'errors': form.errors}, json_dumps_params={'ensure_ascii': False})
    return JsonResponse({'status': False, 'errors': '数据不存在.'})


# 传统方式提交保存
# def user_add(request):
#     if request.method == 'GET':
#         form = UserForm()  # 定义ModelForm实例
#         return render(request, 'user_add.html', {'form': form, 'title': '用户管理 - 添加用户'})
#     # 数据校验
#     form = UserForm(data=request.POST)
#     if form.is_valid():
#         # 数据合法,保存到数据库
#         # print(form.cleaned_data)
#         form.save()
#         return redirect('/user/list/')
#     else:
#         return render(request, '/user/list/', {"form": form})


# 删除用户
def user_delete(request):
    userid = request.GET.get('userid')
    row = Users.objects.filter(id=userid).first()
    if row.admin:
        return JsonResponse({'status': False, 'errors': '管理员不能删除.'})
    else:
        row.delete()

    return JsonResponse({'status': True})

def user_select_fields(request):
    fields_str = request.GET.get('f')
    sel_fields = fields_str.split(',')
    # print(type(sel_fields))
    fields_to_save(request.session['info']['employeeid'], Users, sel_fields)
    return JsonResponse({'status': True})